package com.thread.threadfirst.studyThread2;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 6、上面的还可以用Lock和Condition来实现
 * 对比5和6，Lock和Condition比synchronized、wait、notify更能精确的指定唤醒哪些线程。
 */
public class T5<T> {
    private final LinkedList<T> lists = new LinkedList();
    private final int MAX = 10;     //最多10个元素
    private int count = 0;

    private Lock lock = new ReentrantLock();
    private Condition producer = lock.newCondition();    //await、signal是通过这2个condition来调用的
    private Condition consumer = lock.newCondition();

    public void put(T t) {
        lock.lock();
        try {
            while (lists.size() == MAX) {
                producer.await();
            }
            lists.add(t);
            count++;
            consumer.signalAll();     //消费者全部唤醒
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public T get() {
        T t = null;
        lock.lock();
        try {
            while (lists.size() == 0) {
                consumer.await();
            }
            t = lists.removeFirst();
            count--;
            producer.signalAll();      //生产者全部唤醒
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return t;
    }

    public static void main(String[] args) {
        T5<String> t5 = new T5<>();
        //启动消费者
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {       //这里的5次循环 代表每个消费者线程从容器中get5次，而这5次并不一定是连续get的，是由线程调度器决定的。即10个消费者线程就共get50次。
                    System.out.println(t5.get());
                }
            }, "c" + i).start();
        }

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //启动生产者
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int j = 0; j < 25; j++) {        //这里的25次循环 代表1每个生产者线程从容器中put25次，而这5次并不一定是连续put的，是由线程调度器决定的。即2个生产者线程就共put50次。
                    t5.put(Thread.currentThread().getName() + " " + j);
                }
            }, "p" + i).start();
        }
    }
}
